﻿using System;
using System.Reflection;
using Microsoft.Phone.Tasks;

namespace Columbus
{
    /// <summary>
    /// Chooser result encapsulates chooser result and behavior to call back view model and pass this result
    /// </summary>
    public class ChooserResult
    {
        private readonly string navigatorFrameName;
        private readonly MethodInfo callback;
        private readonly Type viewModelType;

        /// <summary>
        /// Gets or sets result.
        /// </summary>
        /// <value>Result.</value>
        public TaskEventArgs Result { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ChooserResult"/> class.
        /// </summary>
        /// <param name="result"><see cref="Microsoft.Phone.Tasks.TaskEventArgs"/> instance containing the event data.</param>
        /// <param name="navigator">Navigator.</param>
        /// <param name="callback">Callback.</param>
        /// <param name="viewModelType">Type of view model.</param>
        public ChooserResult(TaskEventArgs result, INavigator navigator, MethodInfo callback, Type viewModelType)
        {
            navigatorFrameName = navigator.NavigationFrameName;
            this.callback = callback;
            this.viewModelType = viewModelType;
            Result = result;
        }

        /// <summary>
        /// Sends result to view model.
        /// </summary>
        /// <param name="viewModel">View model.</param>
        public void Complete(ViewModel viewModel)
        {
            var navigator = viewModel.Navigator;
            if (navigator == null)
                throw new ViewModelIsNotInitializedException();

            if (navigator.NavigationFrameName != navigatorFrameName || viewModelType != viewModel.GetType()) 
                return;

            callback.Invoke(viewModel, new object[] { Result });
        }
    }
}